"use client"
import React, { useEffect, useState } from "react";
import {
    Button,
    Col,
    Form,
    Input,
    message,
    Modal,
    Popconfirm,
    Row,
    Select,
    Space,
    Table,
    TableProps,
    Tooltip,
} from 'antd';
import renderIcons from "@/components/CustomIconSelector/conponents";



import { changeUserStatus, delUser, listUser } from "@/clientApi/system/user";
import { DatePicker } from 'antd';
import { DeleteOutlined, PlusOutlined, QuestionCircleOutlined } from "@ant-design/icons";
import EditDictType from "./component/EditDictType";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { delType, listType, refreshCache } from "@/clientApi/system/dict/type";
import { globalMessage } from "@/utils/message";
import { useRouter } from 'next/navigation';
import RenderIconsCustom from "@/components/CustomIconSelector/conponents";

const DictView: React.FC = () => {
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined,
        deptId: undefined,
        params: null,
        beginTime: null,
        endTime: null,

    };

    interface DataType {
    }
    const navigateTo = useRouter();
    const [form] = Form.useForm();
    const [record, setRecord] = useState<Record<string, any>>({});
    const [forceUpdateKey, setForceUpdateKey] = useState(0); // 用于强制更新组件的 key
    const [dataList, setDataList] = useState<DataType[]>([]);
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '字典编号',
            dataIndex: 'dictId',
            key: 'userId',
            width: '200',
            align: 'center',
        },
        {
            title: '字典名称',
            dataIndex: 'dictName',
            key: 'dictName',
            align: 'center',
        },
        {
            title: '字典类型',
            dataIndex: 'dictType',
            key: 'dictType',
            align: 'center',
            render: (_, record: any) => (
                <Space size="middle">
                    <Button
                        type="link"
                        size="small"
                        onClick={() => handleNavicate(record)} >{record.dictType}</Button>
                </Space>)
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
        }, {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            align: 'center',
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
            render: (_, record: any) => (
                <Space size="middle">
                    {record.status == 0 ? "正常" : "停用"}
                </Space>)
        }, {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            render: (_, record: any) => (
                <Space size="middle">
                    {record?.userId !== 1 && (
                        <Tooltip title="修改">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="edit" />}
                                onClick={() => EditClick(record)} />
                        </Tooltip>

                    )}
                    {record?.userId !== 1 && (
                        <Popconfirm
                            title="删除"
                            okText="确认"
                            cancelText="取消"
                            description={'确认删除名称为"' + record.menuName + '"的数据？'}
                            onConfirm={() => handleDelete(record)}
                            icon={<QuestionCircleOutlined />}>
                            <Button
                                type="link"
                                size="small"
                                icon={<DeleteOutlined />}
                            />
                        </Popconfirm>
                    )}

                </Space>
            ),
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [title, setTitle] = useState('');
    const [open, setOpen] = useState<boolean>(false);
    const [dictId, setDictId] = useState<string | undefined>(undefined);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    const getList = () => {
        listType(queryParams).then((res: any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                key: item.dictId // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    const handleSearch = () => {
        form.validateFields().then(values => {
            console.log(values, 'values')
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                dictName: values.dictName,
                status: values.status,
                dictType: values.dictType,
                beginTime: values.dateRange ? values.dateRange[0].format("YYYY-MM-DD") : null,
                endTime: values.dateRange ? values.dateRange[1].format("YYYY-MM-DD") : null,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    // 修改按钮
    const EditClick = (e: any) => {
        setDictId(e.dictId)
        setTitle("修改用户")
        setOpen(true)
    }
    // 删除按钮
    const handleDelete = (e: any) => {
        const dictIds = e.dictId;
        // 用户点击“确定”按钮后执行的操作
        delType(dictIds).then((res: any) => {
            if (res.code === 200) {
                globalMessage().warning("删除成功").then(r => { })
            } else {
                globalMessage().warning(res.msg).then(r => { })
            }
            getList()
        })

    }
    // 刷新缓存
    const handleRefreshCache = () => {
        refreshCache().then((res: any) => {
            globalMessage().success(res.msg)
        });
    }
    // 跳转到对应的路由
    const handleNavicate = (row: any) => {
        console.log(row, 'row')
        navigateTo.push(`/system/dict/${row.dictId}`)
    }


    return (
        <div className='home'>
            <Row gutter={20} style={{ paddingTop: "20px" }}>
                <Col span={24}>
                    <div><Form
                        form={form}
                        name="customized_form_controls"
                        style={{ marginTop: 10, marginLeft: 10, marginBottom: 10 }}
                        layout={useResponsiveLayout("inline")}>
                        <Form.Item
                            name="dictName"
                            label="字典名称">
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="dictType"
                            label="字典类型">
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="status"
                            label="状态">
                            <Select
                                style={{
                                    width: 120,
                                }}

                                allowClear
                                options={[
                                    {
                                        value: 0,
                                        label: '正常',
                                    }, {
                                        value: 1,
                                        label: '停用',
                                    },
                                ]}
                            />
                        </Form.Item>
                        <Form.Item
                            name="dateRange"
                            label="日期">
                            <DatePicker.RangePicker format="YYYY-MM-DD" />
                        </Form.Item>

                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                marginRight: 20,
                            }}>
                                查询
                            </Button>
                            <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <div>
                        <Button type="primary" ghost onClick={() => {
                            setOpen(true);
                            setDictId(undefined);
                            setTitle("新增用户")
                        }} style={{ margin: 10 }}>
                            新增
                        </Button>
                        <Button type="primary" ghost onClick={() => {
                            handleRefreshCache()
                        }} style={{ margin: 10 }}>
                            刷新缓存
                        </Button>
                    </div>
                    <Table<DataType> scroll={{ x: 'max-content' }} columns={columns} dataSource={dataList} pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onChange: handleTableChange
                    }} />
                </Col>
            </Row>
            {open && <EditDictType title={title} open={open} dictId={dictId} OnCanCle={() => {
                setOpen(false);
                getList();
            }} />}
        </div>
    )
};
export default DictView;
